import { world } from "@minecraft/server";
import { PlayerGroup } from "@sapi-game/gamePlayer/playerGroup";
import { GameComponent } from "@sapi-game/main";
import { RandomUtils } from "@sapi-game/utils";
import { CvSMainState } from "../mainState";
import { CvSPlayer } from "../module";
import { EffectIds } from "@sapi-game/utils/vanila-data";

export class CvSRespawn extends GameComponent<CvSMainState> {
    override onAttach(): void {
        this.subscribe(world.afterEvents.entityDie, ({ deadEntity }) => {
            const ans = this.context.groupSet.findById(deadEntity.id);
            if (!ans) return;
            this.handleDie(ans.group);
        });
        //订阅重生事件
        this.subscribe(world.afterEvents.playerSpawn, (t) => {
            const ans = this.context.groupSet.findById(t.player.id);
            if (ans) {
                this.handleRespawn(ans.player, ans.group);
            }
        });
    }

    handleRespawn(player: CvSPlayer, group: PlayerGroup<CvSPlayer>) {
        if (!player.player || this.context.winner != null) return;
        if (group == this.context.shepherd) {
            player.clear(this.state.ironSword.typeId); //清铁剑
            player.giveItem(this.state.ironSword); //重新给
        } else if (group == this.context.chicken) {
            player.player.addEffect(EffectIds.Invisibility, 40, {
                showParticles: false,
            });
        }
    }

    handleDie(group: PlayerGroup<CvSPlayer>) {
        const { chicken, shepherd, groupSet } = this.context;
        if (group == chicken) {
            this.context.lives--;
            groupSet.sendMessage(
                `§a有一个小鸡去世了 §r(剩余${this.context.lives}命)`
            );
            if (this.context.lives == 0) {
                this.state.end("shepherd");
                return;
            }
            return;
        }

        if (group == shepherd) {
            groupSet.sendMessage("§b有一个猎人去世了");
        }
    }
}
